/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.sanerzone.smscenter.modules.sms.web;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.sanerzone.common.support.sequence.MsgId;
import com.sanerzone.jeebase.common.config.Global;
import com.sanerzone.jeebase.common.persistence.Page;
import com.sanerzone.jeebase.common.utils.DateUtils;
import com.sanerzone.jeebase.common.utils.StringUtils;
import com.sanerzone.jeebase.common.utils.excel.ExportExcel;
import com.sanerzone.jeebase.common.web.BaseController;
import com.sanerzone.smscenter.biz.entity.SmsSendVo;
import com.sanerzone.smscenter.biz.utils.SignHelper;
import com.sanerzone.smscenter.biz.utils.StringHelper;
import com.sanerzone.smscenter.modules.account.entity.BaseAccount;
import com.sanerzone.smscenter.modules.account.service.BaseAccountService;
import com.sanerzone.smscenter.modules.sms.entity.SmsGateway;
import com.sanerzone.smscenter.modules.sms.entity.SmsGatewayGroup;
import com.sanerzone.smscenter.modules.sms.entity.SmsSend;
import com.sanerzone.smscenter.modules.sms.entity.SmsSendPhoneExcel;
import com.sanerzone.smscenter.modules.sms.service.SmsGatewayGroupService;
import com.sanerzone.smscenter.modules.sms.service.SmsGatewayService;
import com.sanerzone.smscenter.modules.sms.service.SmsSendService;
import com.sanerzone.smscenter.modules.sms.web.util.ControllerUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 短信发送Controller
 * @author zhukc
 * @version 2017-06-26
 */
@Controller
@RequestMapping(value = "${adminPath}/sms/smsSend")
public class SmsSendController extends BaseController {

	@Autowired
	private SmsSendService smsSendService;

	@Autowired
	private BaseAccountService baseAccountService;

	@Autowired
	private SmsGatewayGroupService smsGatewayGroupService;
	@Autowired
	private SmsGatewayService smsGatewayService;

	@ModelAttribute
	public SmsSend get(@RequestParam(required = false, value = "id") String id) {
		SmsSend entity = null;
		if (StringUtils.isNotBlank(id)) {
			String tableIndex = getTableIndex(id);
			if (Integer.parseInt(tableIndex) > 31 || Integer.parseInt(tableIndex) < 1) {
				Calendar current = Calendar.getInstance();
				tableIndex = String.valueOf(current.get(Calendar.DAY_OF_MONTH));
			}
			SmsSend param = new SmsSend();
			param.setTableName("sms_send_" + tableIndex);
			param.setId(id);
			entity = smsSendService.getV2(param);
		}
		if (entity == null) {

			entity = new SmsSend();

		}
		return entity;
	}

	@RequiresPermissions("sms:smsSend:view")
	@RequestMapping(value = "index")
	public String index(SmsSend smsSend, HttpServletRequest request, HttpServletResponse response, Model model) {
		return "modules/sms/smsSendList";
	}

	@RequiresPermissions("sms:smsSend:view")
	@RequestMapping(value = {"list", ""})
	public String list(SmsSend smsSend, HttpServletRequest request, HttpServletResponse response, Model model) {
//		ControllerUtil.removeComma( smsSend );//去除逗号
		String tableName = "sms_send_" + DateUtils.getTableIndex(smsSend.getSendTimeQ());
		smsSend.setTableName(tableName);
		Page<SmsSend> page = smsSendService.findPage(new Page<SmsSend>(request, response), smsSend);
		page.setOrderBy("create_time desc");
		model.addAttribute("page", page);
		if (smsSend.getSendStatus() != null && smsSend.getSendStatus().charAt(0) == 'V') {
			return "modules/sms/smsSendListCheck";//到提单审核页面
		} else if (smsSend.getSendStatus() != null && smsSend.getSendStatus().charAt(0) == 'T') {//到已发送页面
			return "modules/sms/smsSendListSended";
		} else if (smsSend.getSendStatus() != null && smsSend.getSendStatus().charAt(0) == 'D') {//到待发送页面
			return "modules/sms/smsSendListWaitToSent";
		}else if (smsSend.getSendStatus()!=null && smsSend.getSendStatus().charAt( 0 )== 'X'){
			return "modules/sms/smsSendListWaitToConfirm";
		}
		//如果为列出所有短信，过滤验证码
//		page = smsSendService.findPage(new Page<SmsSend>(request, response), smsSend);
		model.addAttribute("page", page);
		return "modules/sms/smsSendList";
	}

	/**
	 * 提单审核
	 *
	 * @param smsSend
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sms:smsSend:view")
	@RequestMapping(value = "check")
	public String check(SmsSend smsSend, HttpServletRequest request, HttpServletResponse response, Model model) {
		String tableName = "sms_send_" + DateUtils.getTableIndex(smsSend.getSendTimeQ());
		smsSend.setTableName(tableName);
		Page<SmsSend> page = smsSendService.findPage(new Page<SmsSend>(request, response), smsSend);
		page.setOrderBy("create_time desc");
		long count = getCountForPage(page);
		model.addAttribute("count", count);
		model.addAttribute("page", page);
		return "modules/sms/smsSendListCheck";
	}
	/**
	 * 提单记录
	 *
	 * @param smsSend
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sms:smsSend:view")
	@RequestMapping(value = "record")
	public String record(SmsSend smsSend, HttpServletRequest request, HttpServletResponse response, Model model) {
		String tableName = "sms_send_" + DateUtils.getTableIndex(smsSend.getSendTimeQ());
		smsSend.setTableName(tableName);
		//不查行业短信
		smsSend.setNoSmsType("100");
		Page<SmsSend> page = smsSendService.findPage(new Page<SmsSend>(request, response), smsSend);
		page.setOrderBy("create_time desc");
		model.addAttribute("page", page);
		long count = getCountForPage(page);
		model.addAttribute("count", count);
		return "modules/sms/smsSendListRecord";
	}

	/**
	 * 待发短信
	 *
	 * @param smsSend
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sms:smsSend:view")
	@RequestMapping(value = "waitToSent")
	public String waitToSent(SmsSend smsSend, HttpServletRequest request, HttpServletResponse response, Model model) {
		String tableName = "sms_send_" + DateUtils.getTableIndex(smsSend.getSendTimeQ());
		smsSend.setTableName(tableName);
		//不查行业短信
		Page<SmsSend> page = smsSendService.findPage(new Page<SmsSend>(request, response), smsSend);
		page.setOrderBy("create_time desc");
		model.addAttribute("page", page);
		long count = getCountForPage(page);
		model.addAttribute("count", count);
		return "modules/sms/smsSendListWaitToSent";
	}

	/**
	 * 已发短信
	 *
	 * @param smsSend
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sms:smsSend:view")
	@RequestMapping(value = "sented")
	public String sented(SmsSend smsSend, HttpServletRequest request, HttpServletResponse response, Model model) {
		String tableName = "sms_send_" + DateUtils.getTableIndex(smsSend.getSendTimeQ());
		smsSend.setTableName(tableName);
		//不查行业短信
		Page<SmsSend> page = smsSendService.findPage(new Page<SmsSend>(request, response), smsSend);
		page.setOrderBy("create_time desc");
		model.addAttribute("page", page);
		long count = getCountForPage(page);
		model.addAttribute("count", count);
		return "modules/sms/smsSendListSended";
	}

	/**
	 * 提单记录添加备注
	 *
	 * @param smsSend
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sms:smsSend:view")
	@RequestMapping(value = "recordRemark")
	public String recordRemark(SmsSend smsSend, Model model) {
		model.addAttribute("smsSend", smsSend);
		return "modules/sms/smsSendListRecordRemark";
	}

	/**
	 * 提单记录二级菜单
	 *
	 * @param smsSend
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sms:smsSend:view")
	@RequestMapping(value = "recordMore")
	public String recordMore(SmsSend smsSend, Model model) {
		model.addAttribute("smsSend", smsSend);
		return "modules/sms/smsSendListRecordMore";
	}

	@RequiresPermissions("sms:smsSend:view")
	@RequestMapping(value = "formCheck")
	public String form(SmsSend smsSend, Model model) {
		model.addAttribute("smsSend", smsSend);
		return "modules/sms/smsSendCheckForm";
	}

	/**
	 * 审核二级菜单页面
	 *
	 * @param smsSend
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sms:smsSend:view")
	@RequestMapping(value = "smsSendListCheckMore")
	public String sendMore(SmsSend smsSend, Model model) {
		model.addAttribute("smsSend", smsSend);
		return "modules/sms/smsSendListCheckMore";
	}

	@RequiresPermissions("sms:smsSend:edit")
	@RequestMapping(value = "save")
	public String save(SmsSend smsSend, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, smsSend)) {
			return form(smsSend, model);
		}
		if (StringUtils.isNotBlank(smsSend.getId())) {
			smsSend.setTableName("sms_send_" + getTableIndex(smsSend.getId()));
		} else {
			smsSend.setTableName("sms_send_" + getTableIndex(null));
		}
		smsSendService.save(smsSend);
		addMessage(redirectAttributes, "保存短信发送成功");
		return "redirect:" + Global.getAdminPath() + "/sms/smsSend/?repage";
	}

	@RequiresPermissions("sms:smsSend:edit")
	@RequestMapping(value = "saveRemark")
	public String saveRemark(SmsSend smsSend, Model model, RedirectAttributes redirectAttributes) {
		if (StringUtils.isNotBlank(smsSend.getRemark())) {
			if (StringUtils.isNotBlank(smsSend.getId())) {
				smsSend.setTableName("sms_send_" + getTableIndex(smsSend.getId()));
			} else {
				smsSend.setTableName("sms_send_" + getTableIndex(null));
			}
			smsSendService.updateRemark(smsSend);
			addMessage(redirectAttributes, "保存备注成功");
		} else {
			addMessage(redirectAttributes, "备注信息不能为空");
		}
		return "redirect:" + Global.getAdminPath() + "/sms/smsSend/record?repage";
	}

	@RequiresPermissions("sms:smsSend:edit")
	@RequestMapping(value = "delete")
	public String delete(SmsSend smsSend, RedirectAttributes redirectAttributes) {
		smsSendService.delete(smsSend);
		addMessage(redirectAttributes, "删除短信发送成功");
		return "redirect:" + Global.getAdminPath() + "/sms/smsSend/?repage";
	}
	private Object lock=new Object();
	@RequiresPermissions("sms:smsSend:edit")
	@RequestMapping(value = "setSendStatus")
	public String setSendStatus(String ids, String type, String sendStatus, SmsSend smsSend, HttpServletResponse response, Model model) {
		String[] idArray=ids.split( ";" );

		for (int i=0;i<idArray.length;i++){
			String id=idArray[i];
			SmsSend smsSendV=new SmsSend( );
			smsSendV.setId( id );
			String tableIndex = getTableIndex(id);
			if (Integer.parseInt(tableIndex) > 31 || Integer.parseInt(tableIndex) < 1) {
				Calendar current = Calendar.getInstance();
				tableIndex = String.valueOf(current.get(Calendar.DAY_OF_MONTH));
			}
			smsSendV.setTableName( "sms_send_" + tableIndex );
			SmsSend smsSend1=smsSendService.getV2(smsSendV );
			if (smsSend1==null||"0".equals(smsSend1.getIsEffective())){
				return renderString(response, "不要重复审核已审核过的任务".toString(), "application/json");
			}
		}
		synchronized (lock){
			String message = "设置失败";
			if (ids == null) {
				ids = smsSend.getIds();
			}
			String content = smsSend.getSmsContent();
			boolean flag = false;
			if (!Strings.isNullOrEmpty(ids)) {
				//这个type没用
				flag = smsSendService.setSMSstatus(1, sendStatus, ids, content);
				if (flag) {

					message = "设置成功";

				}
			}
			model.addAttribute("message", message);
			if ("batch".equals(type)) {
				smsSend = new SmsSend();
				return "modules/sms/smsSendListCheck";
			}
			return renderString(response, message.toString(), "application/json");
		}

	}

	@RequiresPermissions("sms:smsSend:edit")
	@RequestMapping(value = "setSendStatusJudge")
	public String setSendStatusJudge(String ids, String type, String sendStatus, SmsSend smsSend, HttpServletResponse response, Model model) {
		String[] idsArray = ids.split(";");
		String message = "合法";
		String content = "";
		for (int i = 0; i < idsArray.length; i++) {
			String id = idsArray[i];
			SmsSend entity = null;
			if (StringUtils.isNotBlank(id)) {
				String tableIndex = getTableIndex(id);
				if (Integer.parseInt(tableIndex) > 31 || Integer.parseInt(tableIndex) < 1) {
					Calendar current = Calendar.getInstance();
					tableIndex = String.valueOf(current.get(Calendar.DAY_OF_MONTH));
				}
				SmsSend param = new SmsSend();
				param.setTableName("sms_send_" + tableIndex);
				param.setId(id);
				entity = smsSendService.getV2(param);
				if (i == 0) {
					content = entity.getSmsContent();
				}
				if (!"1".equals(entity.getIsEffective())) {
					//如果已经失效
					message = "有失效";
					break;
				} else {
					String contentTemp = entity.getSmsContent();
					if (!contentTemp.equals(content)) {
						message = "不合法";
						break;
					}

				}
			}

		}


		return renderString(response, message.toString(), "application/json");
	}


	//batchCheckForm
	@RequiresPermissions("sms:smsSend:view")
	@RequestMapping(value = "batchCheckForm")
	public String batchCheckForm(String ids, SmsSend smsSend, HttpServletResponse response, String smsContent, Model model) {
		String id = ids.split(";")[0];
		SmsSend smsSend1 = get(id);
		smsSend1.setIds(ids);
		model.addAttribute("smsSend", smsSend1);
		return "modules/sms/smsSendBatchCheckForm";
	}

	//setSingleCheck
	@RequiresPermissions("sms:smsSend:edit")
	@RequestMapping(value = "setSingleCheck")
	public String setSingleCheck(String ids, SmsSend smsSend, HttpServletResponse response, String smsContent, Model model) {
		synchronized (lock){
			String message = "设置失败";
			String isEffective = smsSend.getIsEffective();
			if ("0".equals(isEffective)) {
				message = "不要重复审核!";
				model.addAttribute("message", message);
				return "modules/sms/smsSendCheckForm";
			}

			boolean flag = false;
			if (!Strings.isNullOrEmpty(ids)) {
				smsSend.setSmsContent(smsContent);
				SmsSendVo smsSendVo = ControllerUtil.SmsSendToVo(smsSend);
				flag = smsSendService.check(smsSendVo);
				if (flag) {
					message = "设置成功";
				}
			}
			model.addAttribute("message", message);
			return "modules/sms/smsSendCheckForm";
		}

	}

	//try send
	@RequiresPermissions("sms:smsSend:edit")
	@RequestMapping(value = "trySend")
	public String setSingleCheck(String content, String phone, String gwCode, RedirectAttributes redirectAttributes) {
		synchronized (lock){
			String message = "发送失败";
			boolean flag = false;
			SmsSendVo smsSend = new SmsSendVo();
			smsSend.setSmsContent(content);
			smsSend.setPhone(phone);
			flag = smsSendService.trySendByGWCode(smsSend, gwCode);
			if (flag) {
				message = "发送成功";
			}

			addMessage(redirectAttributes, message);
			return "redirect:modules/sms/gatewayTest";
		}

	}

	@RequiresPermissions("sms:smsSend:edit")
	@RequestMapping(value = "setWaitSended")
	public String setWaitSended(SmsSend smsSend, String groupId, String gwCode, HttpServletResponse response) {
//		if (!("".equals( groupId ))&&Integer.parseInt( groupId )>3){
//			return renderString(response,"当前是支持3类groupid", "application/json");
//
//		}
		synchronized (lock){
			String message = "设置失败";
			SmsSendVo smsSendVo = ControllerUtil.SmsSendToVo(smsSend);
			boolean flag = false;
			if (smsSendVo.getIsEffective() != null && smsSendVo.getIsEffective().equals("0")) {
				message = "不要重复发送";
			} else {
				flag = smsSendService.waitSended(smsSendVo, groupId, gwCode);
				if (flag) {
					message = "设置成功";
				}
			}

			return renderString(response, message.toString(), "application/json");
		}
	}


	@RequiresPermissions("sms:smsSend:edit")
	@RequestMapping(value = "setSucOrFalse")
	public String setSucOrFalse(String ids, HttpServletRequest request, HttpServletResponse response, Model model,String sendStatus) {
		String message = "设置失败";
		boolean falg=false;
		synchronized (lock){
			falg=smsSendService.setSucOrFalse( ids,sendStatus );
			if (falg) {
				message = "设置成功";
			}
		}

		return renderString(response, message.toString(), "application/json");
	}

	@RequiresPermissions("sms:smsSend:edit")
	@RequestMapping(value = "setWaitBatchSended")
	public String setWaitBatchSended(SmsSend smsSend, String groupId, String gwCode, HttpServletResponse response, Model model) {
		synchronized (lock){
			String ids = smsSend.getIds();
			String[] idArray = ids.split(";");
			String message = "设置成功";
			int length = idArray.length;
			int errorCount = 0;

			for (int i = 0; i < length; i++) {
				String idTemp = idArray[i];
				SmsSend smsSend1 = get(idTemp);
				SmsSendVo smsSendVo = ControllerUtil.SmsSendToVo(smsSend1);
				if (smsSendVo.getIsEffective() != null && smsSendVo.getIsEffective().equals("0")) {
					message = "不要重复发送";
					model.addAttribute("message", message);
					return renderString(response, message.toString(), "application/json");
				}
			}
			for (int i = 0; i < length; i++) {
				String idTemp = idArray[i];
				SmsSend smsSend1 = get(idTemp);
				SmsSendVo smsSendVo = ControllerUtil.SmsSendToVo(smsSend1);
				boolean flag = smsSendService.waitSended(smsSendVo, groupId, gwCode);
				if (!flag) {
					errorCount++;
				}
			}
			message = "其中" + length + "个订单,发送成功:" + (length - errorCount) + "个,发送失败:" + errorCount + "个。";

			model.addAttribute("message", message);
			return renderString(response, message.toString(), "application/json");
		}
	}


	/**
	 * 根据业务ID获取表名下标
	 *
	 * @param bizid
	 * @return
	 */
	public static String getTableIndex(String bizid) {
		if (StringUtils.isNotBlank(bizid)) {
			return String.valueOf(new MsgId(bizid).getDay());
		} else {
			return "";
		}
	}

	@RequiresPermissions("sms:smsSendMessage:send")
	@RequestMapping(value = "sendMessageList")
	public String sendMessageList(SmsSend smsSend, HttpServletRequest request, HttpServletResponse response, Model model) {
		List<SmsGatewayGroup> groups = smsGatewayGroupService.findList(null);
		model.addAttribute("groups", groups);
		return "modules/sms/smsSendMessageForm";
	}

	//waitSendForm
	@RequiresPermissions("sms:smsSendMessage:send")
	@RequestMapping(value = "waitSendForm")
	public String waitSendForm(SmsSend smsSend, HttpServletRequest request, HttpServletResponse response, Model model) {
		List<SmsGatewayGroup> groups = smsGatewayGroupService.findList(null);
		List<SmsGateway> smsGateways = smsGatewayService.findList(null);


		model.addAttribute("smsGateways", smsGateways);
		model.addAttribute("groups", groups);
		return "modules/sms/waitSendForm";
	}

	//waitSendBatchForm
	@RequiresPermissions("sms:smsSendMessage:send")
	@RequestMapping(value = "waitSendBatchForm")
	public String waitSendBatchForm(SmsSend smsSend, HttpServletRequest request, HttpServletResponse response, Model model, String ids) {
		List<SmsGatewayGroup> groups = smsGatewayGroupService.findList(null);
		List<SmsGateway> smsGateways = smsGatewayService.findList(null);
		smsSend.setIds(ids);
		model.addAttribute("smsSend", smsSend);
		model.addAttribute("smsGateways", smsGateways);
		model.addAttribute("groups", groups);
		return "modules/sms/waitSendBatchForm";
	}

	@RequiresPermissions("sms:smsSendMessage:send")
	@RequestMapping(value = "send")
	public String send(SmsSend smsSend, HttpServletRequest request, HttpServletResponse response, Model model) {
		Map<String, String> map = new HashMap<String, String>();
		BaseAccount account = new BaseAccount();
		account.setUserid(smsSend.getUserid());
		account.setServiceId(smsSend.getAccId());
		String result = "";
		BaseAccount baseAccount = baseAccountService.getByUserid(account);
		List<SmsGatewayGroup> groups = smsGatewayGroupService.findList(null);
		model.addAttribute("groups", groups);
		if (baseAccount == null || !StringUtils.equals(baseAccount.getAccStatus(), "1")) {
			result = "账号不存在或未上线";
			model.addAttribute("result", result);
			return "modules/sms/smsSendMessageForm";
		}
		Map<String, Object> accountMap = baseAccountService.getDBMap(baseAccount.getId());
		if (accountMap == null || accountMap.size() <= 0) {
			result = "账号应用不对不存在";
			model.addAttribute("message", result);
			return "modules/sms/smsSendMessageForm";
		}
		if (accountMap.get("groupId") == null) {
			result = "账号应用未分配通道分组";
			model.addAttribute("message", result);
			return "modules/sms/smsSendMessageForm";
		}
//		if (!accountMap.get("groupId").equals(smsSend.getGatewayGroup())) {
//			result = "账号应用通道分组不匹配";
//			model.addAttribute( "message",result );
//			return "modules/sms/smsSendMessageForm";
//		}
		if (accountMap.get("apikey") == null) {
			result = "账号应用未密钥未分配";
			model.addAttribute("message", result);
			return "modules/sms/smsSendMessageForm";
		}
		if (Strings.isNullOrEmpty(smsSend.getPhone()) || smsSend.getPhone().length() != 11) {
			result = "手机号码不是11位";
			model.addAttribute("message", result);
			return "modules/sms/smsSendMessageForm";
		}
		if ("".equals(getSign(smsSend.getSmsContent()))) {
			result = "签名不能为空";
			model.addAttribute("message", result);
			return "modules/sms/smsSendMessageForm";
		}
		map.put("groupid", accountMap.get("groupId") + "");
		map.put("gatewayId", smsSend.getGatewayId());
		String t = System.currentTimeMillis() + "";
		String apiUrl = Global.getConfig("flow.api.url");
		map.put("userid", smsSend.getUserid());
		map.put("appid", baseAccount.getId());
		map.put("ts", t);
		map.put("mobile", smsSend.getPhone());
		map.put("msgcontent", smsSend.getSmsContent());
		String feeType = (String) accountMap.get("feeType");
		if (feeType == null) {
			feeType = "2";//默认为2
		}
		//md5(userid + appid + ts + apikey)
		//		map.put("sign", DigestUtils.md5Hex(smsSend.getUserid() + baseAccount.getId() +  t + accountMap.get("apikey")));

		smsSend.setAccId(baseAccount.getId());
		smsSend.setSmsContentSign(getSign(smsSend.getSmsContent()));
		smsSend.setFeeType(feeType);
		SmsSendVo smsSendVo = new SmsSendVo();
		BeanUtils.copyProperties(smsSend, smsSendVo);


		boolean flag = smsSendService.trySendByGWCode(smsSendVo, smsSend.getGatewayId());
		if (flag == false) {
			result = "发送失败，可能网关code输入有误或者该网关未启用。";
		} else {
			result = "发送成功!";
		}
//		result = HttpRequest.sendPostJson(apiUrl, JSON.toJSONString(map), null, 3000 );
		model.addAttribute("message", result);

		return "modules/sms/smsSendMessageForm";
	}

	//获取签名
	private static String getSign(String content) {
		return SignHelper.get(content);
	}

	public static int smsSize(String smsContent) {
		return StringHelper.smsSize(smsContent);
	}

	@RequestMapping(value = "getSmsType")
	public void getSmsType(BaseAccount baseAccount, HttpServletRequest request, HttpServletResponse response, Model model) {
		BaseAccount account1 = new BaseAccount();
		account1.setId("1");
		account1.setAccName("a");
		BaseAccount account2 = new BaseAccount();
		account2.setId("1");
		account2.setAccName("a");
		BaseAccount account3 = new BaseAccount();
		account3.setId("1");
		account3.setAccName("a");
		List<BaseAccount> accounts = Lists.newArrayList();
		accounts.add(account1);
		accounts.add(account2);
		accounts.add(account3);
		model.addAttribute("aaa", accounts);
	}


	/**
	 * 导出某一个订单中的手机号码（应该会含有多个手机号码）
	 *
	 * @param smsSend
	 * @param request
	 * @param response
	 * @return
	 */
	@RequiresPermissions("sms:smsSendMessage:send")
	@RequestMapping(value = "exprotSmsPhone")
	public String exprotPhoneBySmsId(SmsSend smsSend, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		String phone = smsSend.getPhone();
		String message = "";
		String fileName = "订单号码下载" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		if (StringUtils.isBlank(phone)) {
			message = "订单中手机号码为空";
			return renderString(response, message.toString(), "application/json");
		}
		List<SmsSendPhoneExcel> list = Lists.newArrayList();
		try {
			if (phone.contains(",")) {
				String[] phones = phone.split(",");
				for (int i = 0; i < phones.length; i++) {
					SmsSendPhoneExcel smsSendPhoneExcel = new SmsSendPhoneExcel();
					smsSendPhoneExcel.setPhone(phones[i]);
					list.add(smsSendPhoneExcel);
				}
			} else {
				SmsSendPhoneExcel smsSendPhoneExcel = new SmsSendPhoneExcel();
				smsSendPhoneExcel.setPhone(phone);
				list.add(smsSendPhoneExcel);
			}
			new ExportExcel("订单号码下载", SmsSendPhoneExcel.class).setDataList(list).write(response, fileName).dispose();
		} catch (IOException e) {
			e.printStackTrace();
			addMessage(redirectAttributes, "导出订单号码失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/sms/smsSend/?repage";

	}

	/**
	 * 导出某一批次的发送记录
	 *
	 * @param smsSend
	 * @param request
	 * @param response
	 * @return
	 */
	@RequiresPermissions("sms:smsSendMessage:send")
	@RequestMapping(value = "exprotTaskSendRecord")
	public String exprotTaskSendRecord(SmsSend smsSend, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		SmsSend smsSendVO = new SmsSend();
		smsSendVO.setTaskid(smsSend.getTaskid());
		smsSendVO.setShowLevel("1");
		String tableName = "sms_send_" + DateUtils.getTableIndex(smsSend.getSendTimeQ());
		smsSendVO.setTableName(tableName);
		String fileName = "批号订单导出" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		List<SmsSendPhoneExcel> list = smsSendService.exprotTaskSendRecord(smsSendVO);
		if (null != list && list.size() > 0) {
			for(SmsSendPhoneExcel sms : list) {
				sms.setStatus();
			}
		}
		try {
			new ExportExcel("订单号码下载", SmsSendPhoneExcel.class).setDataList(list).write(response, fileName).dispose();
		} catch (IOException e) {
			e.printStackTrace();
			addMessage(redirectAttributes, "批号订单导出失败！失败信息：" + e.getMessage());
		}
		return null;
	}

	public long getCountForPage(Page<SmsSend> page){
		long count = 0;
		if (null !=page.getList() && page.getList().size() > 0) {
			for (SmsSend send : page.getList()) {
				if (!send.getPhone().contains(",")) {
					count++;
				} else {
					int length =send.getPhone().length() - send.getPhone().replaceAll(",","").length();
					count += length + 1;
				}
			}
		}
		return count;
	}
}